package me.monster.grideaprocessor;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @description
 * @author: Created jiangjiwei in 2020/9/30 11:15
 */
public class FileCounter {
    private List<FileInfo> countFileList = new ArrayList<>();
    private String rootPath = "";

    private FileCounter(String rootPath) {
        this.rootPath = rootPath;
    }

    @NotNull
    public static FileCounter getInstance(String inputPath) {
        return new FileCounter(inputPath);
    }

    List<FileInfo> countFile(String sourcePath, String outputFolder) {
        final File file = new File(sourcePath);
        if (!file.exists()) {
            return Collections.emptyList();
        }
        if (file.isFile()) {
            return Collections.emptyList();
        }
        final File[] listFiles = file.listFiles();
        if (listFiles == null) {
            return Collections.emptyList();
        }
        if (listFiles.length < 1) {
            return Collections.emptyList();
        }
        for (File listFile : listFiles) {
            if (listFile.isHidden()) {
                continue;
            }
            if (listFile.isDirectory()) {
                countFile(listFile.getPath(), outputFolder);
            } else {
                String filePath = listFile.getPath();
                String extension = getExtension(filePath);
                boolean isRoot = !listFile.getPath().replace(sourcePath, "").contains("/");
                final String outputFilePath = filePath.replace(rootPath, outputFolder);
                countFileList.add(new FileInfo(filePath,
                        outputFilePath,
                        !"html".equals(extension), extension, isRoot));
            }
        }
        return countFileList;
    }

    private String getExtension(String path) {
        final int beginIndex = path.lastIndexOf(".");
        if (beginIndex < 0) {
            return "";
        }
        return path.substring(beginIndex + 1);
    }
}
